package com.example.broadcastshareprefence;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private MyReceiver_2 receiver;
    private MyExampleReceiver receiver2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 创建广播接收器实例
        receiver = new MyReceiver_2();
        receiver2 = new MyExampleReceiver();
        // 创建 IntentFilter 来指定要接收的广播类型
        IntentFilter filter = new IntentFilter("com.example.broadcastshareprefence.MY_CUSTOM_ACTION");
        filter.setPriority(100);
        registerReceiver(receiver, filter);

        IntentFilter filter2 = new IntentFilter("com.example.broadcastshareprefence.MY_CUSTOM_ACTION");
        filter2.setPriority(1);
        registerReceiver(receiver2, filter2);

        LocalBroadcastManager.getInstance(this).registerReceiver(receiver2, new IntentFilter("com.example.broadcastshareprefence.MY_CUSTOM_ACTION"));
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("com.example.broadcastshareprefence.MY_CUSTOM_ACTION"));
        Button btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 发送有序广播
                Intent intent = new Intent("com.example.broadcastshareprefence.MY_CUSTOM_ACTION");
                sendOrderedBroadcast(intent, null);
            }
        });
        Button btn2 = findViewById(R.id.button2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 发送外部广播
                Intent intent = new Intent("com.example.broadcastshareprefence.MY_CUSTOM_ACTION");
                sendBroadcast(intent);
            }
        });

        Button btn3 = findViewById(R.id.button3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 发送本地广播
                Intent intent = new Intent("com.example.broadcastshareprefence.MY_CUSTOM_ACTION");
                LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除注册广播接收器
        unregisterReceiver(receiver);
        unregisterReceiver(receiver2);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver2);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }
}